<template>
    <div style="width: 100%;">
        <!-- 搜索表单 -->
        <el-form :inline="true" ref="formRef" :model="formSearch" class="demo-form-inline">
            <el-form-item label="姓名">
                <el-input v-model="formSearch.staffName" placeholder="请输入" clearable @change="formChange" />
            </el-form-item>
            <el-form-item label="职位">
                <el-select v-model="formSearch.position" placeholder="请选择职位" clearable>
                    <el-option v-for="item in departments.positionList" :key="item.value" :label="item.label"
                        :value="item.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="search">
                <el-button type="primary" :icon="Refresh" @click="resetFormInline">重置</el-button>
                <el-button type="primary" :icon="Search" @click="searchData">查询</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮组 -->
        <div class="btn-group">
            <el-button type="danger" @click="handleDelete">删除</el-button>
        </div>
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" border height="420" show-overflow-tooltip
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" label="全选" />
                <el-table-column fixed label="索引" type="index" :index="indexMethod" align="center" width="55" />
                <el-table-column prop="staff_no" label="工号" />
                <el-table-column prop="staff_name" label="姓名" />
                <el-table-column prop="position" label="职位" />
                <el-table-column prop="time" label="加班日期" :formatter="formatTime" />
                <el-table-column prop="duration" label="加班时长" />
                <el-table-column fixed="right" label="操作" width="250">
                    <template #default="scope">
                        <el-button :icon="Edit" text type="success" :disabled="scope.row.audit != 0"
                            @click="handleEdit(scope.row)">审核</el-button>
                        <el-button type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button type="danger" @click="deleteRows(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination class="pagination" v-model:current-page="page.pageNum" v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 弹窗-详情 -->
        <el-dialog class="dialog" v-model="dialogVisible" title="详情" width="800" :close="handleClose">
            <el-form class="dialog-form" :inline="true" :model="dialogForm" ref="dialogFormRef">
                <el-form-item label-width="120px" label="工号">
                    <el-input v-model="dialogForm.staffNo" />
                </el-form-item>
                <el-form-item label-width="120px" label="姓名">
                    <el-input v-model="dialogForm.name" />
                </el-form-item>
                <el-form-item label-width="120px" label="职位">
                    <el-input v-model="dialogForm.position" />
                </el-form-item>
                <el-form-item label-width="120px" label="部门">
                    <el-input v-model="dialogForm.departmentName" />
                </el-form-item>
                <el-form-item label-width="120px" label="加班日期">
                    <el-input v-model="dialogForm.time" />
                </el-form-item>
                <el-form-item label-width="120px" label="加班时长">
                    <el-input v-model="dialogForm.duration" />
                </el-form-item>
                <el-form-item label-width="120px" label="加班事由">
                    <el-input v-model="dialogForm.reason" />
                </el-form-item>
                <el-form-item label-width="120px" label="审核状态">
                    <el-input v-model="dialogForm.audit" :formatter="formatStatus" />
                </el-form-item>
                <el-form-item label-width="120px" label="审核回复">
                    <el-input style="width: 220px;" v-model="dialogForm.review_responses" type="textarea" />
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 弹窗-审核 -->
        <el-dialog class="dialog" v-model="dialogApprovalVisible" title="详情" width="400" :close="handleApprovalClose">
            <el-form class="dialog-form" :model="dialogApprovalForm" ref="dialogApprovalFormRef">
                <el-form-item label-width="80px" label="姓名">
                    <el-input disabled v-model="dialogApprovalForm.name" />
                </el-form-item>
                <el-form-item label-width="80px" label="职位">
                    <el-input disabled v-model="dialogApprovalForm.position" />
                </el-form-item>
                <el-form-item label-width="80px" label="加班日期">
                    <el-input disabled v-model="dialogApprovalForm.time" />
                </el-form-item>
                <el-form-item label-width="80px" label="加班时长">
                    <el-input disabled v-model="dialogApprovalForm.duration" />
                </el-form-item>
                <el-form-item label-width="80px" label="请假事由">
                    <el-input disabled v-model="dialogApprovalForm.reason" />
                </el-form-item>
                <el-form-item label-width="80px" label="审核状态">
                    <el-radio-group v-model="dialogApprovalForm.audit">
                        <el-radio value="2">通过</el-radio>
                        <el-radio value="1">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label-width="80px" label="审核回复">
                    <el-input v-model="dialogApprovalForm.review_responses" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleApprovalClose">关闭</el-button>
                    <el-button type="primary" @click="updateDialog">
                        修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Search, Edit, Refresh } from '@element-plus/icons-vue'
import { queryOvertime, deleteOvertime, updateOvertime, queryEmployees } from "@/api/employee"
import { queryDepartments } from '@/api/department'
import { timeProcessing } from '@/utils/date'

// 分页
const page = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
})

// 表单-搜索-ref
const formRef = ref(null)

// 表单-搜索-数据
const formSearch = reactive({
    staffName: '',
    position: '',
})

// 部门和职位
const departments = reactive({
    departmentList: [],
    positionList: []
})

// 表格数据
const tableData = ref([])

// 审核-弹窗
const dialogApprovalVisible = ref(false);
const dialogApprovalFormRef = ref(null)
const dialogApprovalForm = reactive({})

// 详情-弹窗
const dialogVisible = ref(false)
const dialogFormRef = ref(null)
const dialogForm = reactive({})

const positionListClone = ref(null);

// 多选-id
const ids = ref([]);

// 表格索引
const indexMethod = (index) => {
    return page.pageSize * (page.pageNum - 1) + index + 1
}

// 格式化时间
const formatTime = (row, column, cellValue) => {
    return timeProcessing(cellValue, "date")
}

// 格式化审核状态
const formatStatus = (status) => {
    let str = '';
    if (status == 0) str = '未审核';
    if (status == 1) str = '驳回';
    if (status == 2) str = '通过';
    return str
}

// 获取部门和职位
const getDepartments = async () => {
    try {
        const res = await queryDepartments();
        if (res.code === 0) {
            const departmentSet = new Set(departments.departmentList.map(d => d.label));
            res.data.list.forEach(item => {
                if (!departmentSet.has(item.department_name)) {
                    departments.departmentList.push({
                        value: item.department_name,
                        label: item.department_name
                    });
                    departmentSet.add(item.department_name);
                }
                departments.positionList.push({
                    value: item.id,
                    label: item.position
                });
                positionListClone.value = departments.positionList;
            });
        } else {
            ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 重置
const resetFormInline = () => {
    formSearch.staffName = '';
    formSearch.position = '';
    searchData();
}

const formChange = async (value) => {
    formSearch.position = null;
    if (value) {
        const res = await queryEmployees({ staffName: value });
        if (res.code === 0) {
            departments.positionList = [];
            res.data.list.map(item => {
                departments.positionList.push({
                    value: item.id,
                    label: item.position
                });
            })
        }
    } else {
        departments.positionList = positionListClone.value;
    }
}

// 搜索
const searchData = async () => {
    const data = {
        position: formSearch.position,
        staffName: formSearch.staffName,
        pageNum: page.pageNum,
        pageSize: page.pageSize,
    }
    try {
        const res = await queryOvertime(data);
        if (res.code === 0) {
            tableData.value = res.data.list;
            page.total = res.data.total;
        } else {
            // ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 表格多选
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.id);
}

// 删除
const deleteRows = (ids) => {
    const data = {
        ids: Array.isArray(ids) ? ids : [ids]
    };
    ElMessageBox.confirm('确认删除选中项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteOvertime(data);
            if (res.code === 0) {
                ElMessage.success('删除成功！');
                searchData();
            } else {
                ElMessage.error('删除失败！');
            }
        } catch {
            console.log("请求失败");
        }
    }).catch(() => {
        console.log('取消删除');
    })
}

// 多选删除
const handleDelete = () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请选择要删除的签到记录！');
        return;
    }
    deleteRows(ids.value)
}

// 审核-弹窗-修改
const updateDialog = async () => {
    const data = {
        id: dialogApprovalForm.id,
        audit: dialogApprovalForm.audit,
        review_responses: dialogApprovalForm.review_responses,
    }
    try {
        const res = await updateOvertime(data);
        if (res.code == 0) {
            ElMessage.success('修改成功！');
            handleApprovalClose();
            searchData();
        } else {
            ElMessage.error('修改失败！');
        }
    } catch {
        console.log("请求失败");
    }
}

// 详情-弹窗-打开
const handleDetail = (row) => {
    dialogVisible.value = true;
    dialogForm.staffNo = row.staff_no;
    dialogForm.name = row.staff_name;
    dialogForm.position = row.position;
    dialogForm.departmentName = row.department_name;
    dialogForm.time = timeProcessing(row.time);
    dialogForm.duration = row.duration;
    dialogForm.reason = row.reason;
    dialogForm.audit = row.audit;
    dialogForm.review_responses = row.review_responses;
}

// 详情-弹窗-关闭
const handleClose = () => {
    dialogVisible.value = false
    if (dialogFormRef.value) dialogFormRef.value.resetFields();
}

// 审核
const handleEdit = (row) => {
    dialogApprovalVisible.value = true;
    dialogApprovalForm.id = row.id;
    dialogApprovalForm.name = row.staff_name;
    dialogApprovalForm.position = row.position;
    dialogApprovalForm.time = timeProcessing(row.time);
    dialogApprovalForm.duration = row.duration;
    dialogApprovalForm.reason = row.reason;
}

const handleApprovalClose = () => {
    dialogApprovalVisible.value = false
    if (dialogApprovalFormRef.value) dialogApprovalFormRef.value.resetFields();
}

// 分页
const handleSizeChange = (val) => {
    page.pageSize = val
    searchData()
}

const handleCurrentChange = (val) => {
    page.pageNum = val
    searchData()
}

onMounted(() => {
    searchData();
    getDepartments()
})


</script>

<style lang="scss" scoped>
.demo-form-inline {
    padding: 10px 20px 0;
}

.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}

.btn-group {
    box-sizing: border-box;
    padding-right: 20px;
    margin-bottom: 5px;
    margin-top: -15px;
    float: right;
}

.table {
    box-sizing: border-box;
    padding: 0 20px 0 15px;
}

.footer {
    position: relative;
    width: 100%;
    height: auto;
}

.pagination-wrapper {
    width: 100%;
    height: 44px;
    display: flex;
    justify-content: flex-end;
}

.pagination {
    margin-top: 15px;
    margin-right: 20px;
}

:deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
}

.dialog-form {
    .el-input {
        --el-input-width: 220px;
    }
}
</style>